import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MutationRes } from 'src/modules/shared/vo/mutation.res';
import { RoleEntity } from 'src/modules/system/role/entities/role.entity';
import { DeleteResult, getConnection, Repository, UpdateResult } from 'typeorm';
import { ModifyAccountInput } from '../../dto/modifyAccount.input';
import { AccountEntity } from '../../entities/account.entity';
import { AccountRoleEntity } from '../../entities/account.role.entity';

@Injectable()
export class AccountService {
    constructor(
        @InjectRepository(AccountEntity)
        private readonly accountRepository: Repository <AccountEntity>
    ){

    }

    async createAccount(username: string, password: string): Promise<MutationRes>{
       const account = this.accountRepository.create({username, password});
       await this.accountRepository.save(account);
       return {
          code: 0,
          message: '创建成功'
       }
    }

    async deleteAccountById(id: number): Promise<MutationRes>{
      const {raw: {affectedRows}} = await this.accountRepository.softDelete(id);
      if(affectedRows){
         return {
            code: 0,
            message: '删除成功'
         }
      } else {
         return {
            code: 1,
            message: '删除失败'
         }
      }
    }

    async modifyAccountById(id:number, data: ModifyAccountInput): Promise<MutationRes>{
       const row =  await this.accountRepository.findOne(id);
       row.username = data.username;
       row.password = data.password;
       try {
         await this.accountRepository.save(row);
         return {
            code: 0,
            message: '修改成功'
         }
       } catch (error) {
         return {
            code: 1,
            message: '修改失败'
         }
       }
    }

    async accountList(): Promise<any>{
       return await this.accountRepository.find();
    }

    async account(id: number): Promise<any>{
       return await getConnection().createQueryBuilder(AccountEntity, 'account')
       .leftJoin(AccountRoleEntity, 'account_role', 'account.id = account_role.accountId')
       .leftJoinAndMapMany('account.roleList', RoleEntity, 'role', 'account_role.roleId = role.id')
       .where('(account.id = :id)', { id })
       .getOne();
    }

}
